import {useEffect, useRef} from 'react'
import * as echarts from 'echarts'

interface ChartProps {
  options: any
  style?: React.CSSProperties
}

const Chart: React.FC<ChartProps> = ({options, style}) => {
  const chartRef = useRef<HTMLDivElement>(null)
  let chartInstance: echarts.ECharts | null = null

  const renderChart = () => {
    try {
      const renderedInstance = echarts.getInstanceByDom(chartRef.current!)
      if (renderedInstance) {
        chartInstance = renderedInstance
      } else {
        chartInstance = echarts.init(chartRef.current!)
      }
      chartInstance.setOption(options)
    } catch (error) {
      console.error('error', error)
      chartInstance && chartInstance.dispose()
    }
  }

  const resizeHandler = () => {
    chartInstance!.resize()
  }

  useEffect(() => {
    renderChart()

    return () => {
      chartInstance && chartInstance.dispose()
    }
  }, [])

  useEffect(() => {
    window.addEventListener('resize', resizeHandler)
    return () => window.removeEventListener('resize', resizeHandler)
  }, [])

  return (
    <div>
      <div style={style} ref={chartRef} />
    </div>
  )
}

export default Chart
